package com.ccys.cms.service.impl;

import com.ccys.cms.service.CommonService;
import com.ccys.cms.service.userManagement.DoctorService;
import com.ccys.cms.service.userManagement.TblMemberWebService;
import com.ccys.common.third.aws.s3.S3Util;
import com.ccys.common.third.aws.s3.model.S3Credentials;
import com.ccys.common.util.Kit;
import com.ccys.common.util.StringUtil;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.CommonDto;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.*;

import static com.ccys.common.vo.ResponseResult.*;


@Service
public class CommonServiceImpl  implements CommonService {

    @Autowired
    private TblMemberWebService tblMemberWebService;

    @Autowired
    private DoctorService doctorService;

    @Override
    public ResponseResult putS3ObjectByBase64(HttpServletRequest request, CommonDto dto) {
        if(StringUtil.isEmpty(dto.getContent())) {
            return error("参数未传");
        }

        String bbb = Base64.getEncoder().encodeToString(dto.getContent().getBytes());
        byte[] decode = Base64.getDecoder().decode(bbb);
        System.out.println("===上传开始===");
        S3Util.putS3ObjectByByte(dto.getBucketName(),"zifuchuan_bbb.????",decode);
        return success();
    }

    @Override
    public ResponseResult putS3ObjectByInputStream(HttpServletRequest request,CommonDto dto) {
        if(StringUtil.isEmpty(dto.getBucketName())) {
            dto.setBucketName(S3Util.bucketName);
        }
        Map<String,Object> resultMap = new HashMap<>();
        CommonsMultipartResolver mutilpartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        String fileName = Kit.get32UUID().replace("-", "");
        if(StringUtil.isNotEmpty(dto.getDirectory())) {
            fileName = dto.getDirectory() + "/" + fileName;
        }
        //TODO 测试写死
        //fileName = "666.jpg";
        if (mutilpartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> it = multiRequest.getFileNames();
            while (it.hasNext()) {
                String textName = it.next();
                // 获取MultipartFile类型文件
                List<MultipartFile> fileList = multiRequest.getFiles(textName);
                try{
                    for(MultipartFile fileDetail:fileList) {
                        InputStream in = fileDetail.getInputStream();
                        String[] fileNames = fileDetail.getOriginalFilename().split("\\.");
                        fileName = fileName + "." + fileNames[fileNames.length - 1];
                        //通过字节数组上传
                        S3Util.putS3ObjectByByte(dto.getBucketName(), fileName,fileDetail.getBytes());
                        //通过流上传
                        //S3Util.putS3ObjectByInputStream(dto.getBucketName(), fileName, in);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }

        resultMap.put("fileName",fileName);
        /*Result fileUrl = this.getFileUrl(fileName);
        resultMap.put("filePath",fileUrl.getData());*/
        //文件的详细地址根据实际情况拼接
        String url = "https://s3.ap-southeast-1.amazonaws.com/" + dto.getBucketName() +  "/" + fileName;
        resultMap.put("filePathName",url);
        return success(resultMap);
    }

    @Override
    public ResponseResult getSTSInfo(CommonDto dto) {
        S3Credentials assumeRoleSTS = S3Util.getAssumeRoleSTS("??", "??");
        return success(assumeRoleSTS);
    }

    @Override
    public ResponseResult getUploadUrl(CommonDto dto) {
       /* Map<String, String> metadata = Map.of(
            "author", "Bob",
            "version", "1.0.0.0"
        );*/
        String presignedUrl = S3Util.createPresignedUrl(dto.getBucketName(), dto.getName(), null);
        System.out.println("最终使用地址=" + presignedUrl);
        return success(presignedUrl);
    }

    @Override
    public ResponseResult getDownloadUrl(CommonDto dto) {
        String presignedGetUrl = S3Util.createPresignedGetUrl(dto.getBucketName(), dto.getName());
        return success(presignedGetUrl);
    }

    @Override
    public ResponseResult generateIdOrCode(HttpServletRequest request, CommonDto dto) {
        if(StringUtil.isEmpty(dto.getType())) {
            return error("参数未传");
        }
        if("0".equals(dto.getType())) {
            //生成memberCode
            return success(this.tblMemberWebService.getCode());
        }else if ("1".equals(dto.getType())){
            //生成doctor的code
            return success(doctorService.getCode());
        }
        return error();
    }
}
